/**
 * This program is free software but WITHOUT ANY WARRANTY OR CONDITIONS OF ANY KIND.
 *
 * Copyright (C) 2008-2013 www.pretty-tools.com
 */

document.title = chrome.i18n.getMessage("webslideshow_options_title");

function onPageLoad()
{
    yrprxHTMLContentHelper.enumerateElementsByTagName(document, "translate", function(elem) {
        if (elem && elem.innerText && elem.innerText.length > 0)
            elem.innerText = chrome.i18n.getMessage(elem.innerText);
    });
    yrprxHTMLContentHelper.enumerateElementsByTagName(document, "INPUT", function(elem) {
        if (elem && elem.type && elem.type == "button" && elem.value && elem.value.length > 0)
            elem.value = chrome.i18n.getMessage(elem.value);
    });
    yrprxHTMLContentHelper.enumerateElementsByTagName(document, "td", function(elem) {
        if (elem && elem.innerHTML && elem.innerHTML.length > 0) {
            var html = elem.innerHTML;
            var idxStart = html.indexOf("<translate>webslideshow_options_");
            if (idxStart >= 0) {
                var idxEnds = html.indexOf("</translate>");
                if (idxEnds >= 0)
                    elem.innerHTML = html.substring(0, idxStart) + chrome.i18n.getMessage(html.substr(idxStart+11, idxEnds - (idxStart+11))) + html.substr(idxEnds+12, html.length-(idxEnds+12));
            }
        }
    });

    document.getElementById("tabs").selectedIndex = 0;
    onLoad();

    var btCancel = document.getElementById("button-cancel");
    var btOK = document.getElementById("button-ok");
    if (btOK && btCancel && btCancel.clientWidth)
        btOK.style.width = btCancel.clientWidth + "px";

    var openFileForImport = document.getElementById('openFileForImport');
    openFileForImport.addEventListener('change', onImportFileSelected, false);

    var body = document.body;
    body.onclick = hideContextMenu;
    body.onselectstart = defaultForInput;
    body.onkeydown = function () {
        hideContextMenu();
        return onTableKeypress();
    };
    body.oncontextmenu = function () {
        hideContextMenu();
        return defaultForInput();
    };

    var tree_menu_table = document.getElementById("tree_menu_table");
    tree_menu_table.onmouseover = contextmenuOnMouseOver;
    tree_menu_table.onmouseout = contextmenuOnMouseOut;

    document.getElementById("context-add").onclick = function () {
        hideContextMenu();
        onAddRule();
    };
    document.getElementById("context-clone").onclick = function () {
        hideContextMenu();
        onCloneRule();
    };
    document.getElementById("context-edit").onclick = function () {
        hideContextMenu();
        onEditRule();
    };
    document.getElementById("context-remove").onclick = function () {
        hideContextMenu();
        removeRule();
    };
    document.getElementById("context-move-up").onclick = function () {
        hideContextMenu();
        moveRuleUp();
    };
    document.getElementById("context-move-down").onclick = function () {
        hideContextMenu();
        moveRuleDown();
    };

    document.getElementById("OptionsTabButton").onclick = SelectOptionsTab;
    document.getElementById("RulesTabButton").onclick = SelectRulesTab;

    document.getElementById("delay").onkeypress = onlyNumbers;
    document.getElementById("min_size").onkeypress = onlyNumbers;
    document.getElementById("scroll_step").onkeypress = onlyNumbers;
    document.getElementById("zoom_step").onkeypress = onlyNumbers;

    document.getElementById("tree_container").oncontextmenu = onContextMenu;
    document.getElementById("rules_treechildren").onclick = onTableClick;

    document.getElementById("add-rule").onclick = onAddRule;
    document.getElementById("import-rule").onclick = onImportRule;
//    document.getElementById("export-rule").onclick = onExportRule;

    document.getElementById("button-ok").onclick = function () {
        if (onOK()) yrprxBrowser.closeWindow();
    };
    document.getElementById("button-cancel").onclick = function () {
        yrprxBrowser.closeWindow();
    };
    document.getElementById("button-apply").onclick = onOK;
    document.getElementById("button-help").onclick = onHelp;
}

function onlyNumbers()
{
    return /[\d\x00\x08]/.test(String.fromCharCode(window.event.keyCode));
}

function SelectOptionsTab()
{
    document.getElementById("tab_rules").style.display = "none";
    document.getElementById("tab_options").style.display = "inline";
    document.getElementById("OptionsTabButton").className = "SelectedOptionsTab";
    document.getElementById("RulesTabButton").className = "UnSelectedRulesTab";
    document.getElementById("tabs").selectedIndex = 0;
}

function SelectRulesTab()
{
    document.getElementById("tab_options").style.display = "none";
    document.getElementById("tab_rules").style.display = "inline";
    document.getElementById("OptionsTabButton").className = "UnSelectedOptionsTab";
    document.getElementById("RulesTabButton").className = "SelectedRulesTab";
    document.getElementById("tabs").selectedIndex = 1;
}

function onTableClick()
{
    var target = window.event.srcElement;
    var tr = yrprxHTMLContentHelper.getParentWithTag(target, "TR");
    if (!tr && target.tagName == "TR")
        tr = target;
    if (!tr)
        return;

    selectTreeNode(gRuleTreeView.findRowIndex(tr));
}

function onTableKeypress()
{
    var tabs = document.getElementById("tabs");
    if (!tabs || tabs.selectedIndex != 1)
        return true;

    var event = window.event;
    var keyCode = event.keyCode;

    if (keyCode == yrprxKeyboardHelper.VK_UP && !event.ctrlKey)
        selectTreeNode(gRuleTree.currentIndex-1);
    else if (keyCode == yrprxKeyboardHelper.VK_DOWN && !event.ctrlKey)
        selectTreeNode(gRuleTree.currentIndex+1);
    else 
        return !onKeyPressInTree(event);

    return false;
}

function onContextMenu()
{
    onTableClick();
    onPopupContext();
    contextmenuProcessHidden('tree_menu');
    return contextmenuShowMenu('tree_menu');
}

function hideContextMenu()
{
    return contextmenuHideMenu('tree_menu');
}

function defaultForInput()
{
    var active = document.activeElement;
    return active && "INPUT" == active.tagName;
}

function onImportFileSelected(evt) {
    var files = evt.target.files; // FileList object
    if (!files || files.length != 1)
        return;

    var reader = new FileReader();
    reader.readAsBinaryString(files[0]);

    reader.onload = function loaded(evt) {
        // Obtain the read file data
        var fileString = evt.target.result;
        try {
            importRules(wsshWebProfileSerializer.load(fileString));
        } catch(ex) {
            if (gLogger.enabled) gLogger.error("onImportRule: ", ex);
        }
    };

    reader.onerror = function(evt) {
        console.log(evt.target.error);
        if (evt.target.error.code == evt.target.error.NOT_READABLE_ERR) {
            // The file could not be read
            alert(evt.target.error);
        }
    };
}

function onImportRule()
{
    document.getElementById('openFileForImport').click();
}

addEventListener("load", onPageLoad);
